import openpyxl     #插入openpyxl库，生成excel表
wb = openpyxl.Workbook()
ws = wb.active
ws.append(["性别", "年龄", "身高 (cm)", "体重 (kg)", "BMR (kcal/day)"])

def menu():
    while True:
        print("欢迎使用BMR计算程序！")
        choice = input("进入程序请按1，退出程序请按2：")
        if choice in ["1", "2"]:
            return choice
        else:
            print("输入有误，请重新输入。")


def count():         #计算结果并给建议
    while True:
        try:
            gender = input("请输入您的性别（男/女）：")
            if gender not in ["男", "女"]:
                print("输入有误，请重新输入。")
                continue
            age = int(input("请输入您的年龄（岁）："))
            height = float(input("请输入您的身高（厘米）："))
            weight = float(input("请输入您的体重（千克）："))
            if gender == "男":
                bmr = 13.7 * weight + 5.0 * height - 6.8 * age + 66
            elif gender == "女":
                bmr = 9.6 * weight + 1.8 * height - 4.7 * age + 655
            else:
                print("输入有误，请重新输入。")
                continue
            print("您的BMR指数为：{:.2f}".format(bmr))

            if bmr < 1200:
                print("您的BMR值过低，建议通过适当增加饮食摄入量来提高代谢率。")
            elif bmr > 2000:
                print("您的BMR值过高，建议控制饮食并增加适量运动来达到健康的代谢水平。")
            else:
                print("您的BMR值在正常范围内，建议保持健康的饮食和运动习惯，维持正常的代谢水平。")
            return {"Gender": gender, "Age": age, "Height": height, "Weight": weight, "BMR": bmr}
        except ValueError:
            print("输入有误，请重新输入。")


def save_to_excel(gender, age, height_cm, weight_kg, bmr):
    try:
        ws.append([gender, age, height_cm, weight_kg, bmr])
        wb.save("result.xlsx")
        print("结果已保存到Excel文件：result.xlsx")
    except Exception as e:
        print("保存结果失败！错误信息：{}".format(str(e)))


def main():
    while True:
        choice = menu()
        if choice == "1":
            result = count()
            save_to_excel(result["Gender"], result["Age"], result["Height"], result["Weight"], result["BMR"])
        elif choice == "2":  # 退出程序
            print("感谢使用BMR计算器！")
            break
        else:
            print("输入有误，请重新输入。")

if __name__ == "__main__":
    main()
